<?php

use console\db\Migration;
use yii\db\Query;

/**
 * 用户收藏的动态格式化
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000018_t_user_favorite_format extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%user_favorite}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $this->delete($this->tableName, [
            'and',
            ['!=', 'model', 'cms_article'],
            ['!=', 'model', 'sns_dynamic'],
        ]);

        $query = (new Query())->from($this->tableName)
        ->groupBy(['user_id', 'model', 'model_id'])
        ->having('count(*)>1');

        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        if (empty($rows)) {
            return;
        }
        $connect = $migration->db->createCommand();
        foreach ($rows as $row) {
            $connect->delete($migration->tableName, [
                'and',
                ['!=', 'id', $row['id']],
                ['model' => $row['model']],
                ['user_id' => $row['user_id']],
                ['model_id' => $row['model_id']],
            ])->execute();
        }
    }

}
